<template>
  <dialog_item :dialogTitle="$t('select_user')" @onBtnDialogClick="onBtnDialogClick" :visible.sync="dialogVisible" :appendBody="true" dialogClass="user-selectbox user-selectionbox user-selectionbox_header_height" :isShowConfirmBtn="true">
    <el-container class="height100 overflowYHidden">
        <el-tabs type="card" @tab-click="handleClick" class="selectionbox-tabs width70" v-model="activeName">
          <el-tab-pane :label="$t('by_role')" class="tab-pane height90 " name="byRole">
            <el-row  class="height100">
            <el-col :span="6" class="border-r" lass="border-r height100 overflowYScroll">
              <el-table :data="roleData.role" @row-click="roleRowClick"  max-height="384" highlight-current-row >
                  <el-table-column prop="roleName" :label="$t('rolelist')"></el-table-column>
              </el-table>
            </el-col>
            <el-col :span="18" >
              <el-table :data="tableDatabyRole.datas" ref="role"
              @select="selectChange"
              @select-all="selectAllChange"
              @selection-change="changeRoleCheck"
              max-height="384">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="name" :label="$t('user_selection_role_user')"></el-table-column>
                
              </el-table>
              <el-pagination
                @size-change="roleUserSizeChange"
                @current-change="getData"
                :current-page.sync="allId.pageNum"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="allId.pageSize"
                :pager-count=5
                layout="prev, pager, next, total, sizes"
                background
                :total="tableDatabyRole.rowCount?tableDatabyRole.rowCount:0"
              ></el-pagination>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane :label="$t('by_dep')" class="tab-pane height90" name="byDepartment">
          <el-row class="height100">
            <el-col :span="6" class="border-r height100 overflowYScroll userSelectionTree">
              <el-tree
                node-key="id"
                :props="{
                      label: 'name',
                      children: 'zones',
                      isLeaf: 'leaf'
                    }"
                :load="loadNode"
                @node-click="onNodeClick"
                :default-expanded-keys="defaultExpandedKeys"
                :expand-on-click-node="false"
                lazy
                class="overflowYNone"
                :key="timer"
              >
                  <span slot-scope="{ data }">
                      <span :title="data.name">{{ data.name }}</span>
                  </span>              
              </el-tree>
            </el-col>
            <el-col :span="18" >
              <el-table ref="dept" 
              :data="tableData.datas" 
              @select="selectChange" 
              @select-all="selectAllChange"
              @selection-change="changeRoleCheck"
              max-height="384">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="name" :label="$t('user_selection_dep_user')"></el-table-column>

              </el-table>
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="getData"
                :current-page.sync="allId.pageNum"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="allId.pageSize"
                :pager-count=5
                layout="prev, pager, next, total, sizes"
                background
                :total="tableData.rowCount?tableData.rowCount:0"
              ></el-pagination>
            </el-col>
          </el-row>
        </el-tab-pane>
        <!-- <el-tab-pane label="在线用户" class="tab-pane">
          <el-row>
            <el-col :span="24">
              <el-table :data="onlineData.datas" @row-click="onlineRowClick" max-height="384">
                  <el-table-column prop="name" label="在线用户"></el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-tab-pane> -->
        <el-tab-pane :label="$t('query')" class="tab-pane height90" name="byQuery">
          <el-form :inline="true" :model="allId" size="small" class="demo-form-inline" @submit.native.prevent>
            <el-form-item :label="$t('name')">
              <el-input v-model="allId.selectId" :placeholder="$t('username')+'/'+$t('loginno')" @keyup.enter.native="getData"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="getData" type="primary" plain >{{$t('query')}}</el-button>
              <el-button @click="resetSearchTableData">{{$t('reset')}}</el-button>
            </el-form-item>
          </el-form>
          <el-table ref="search"
            :data="tableData.datas" 
            @select="selectChange" 
            @select-all="selectAllChange"
            @selection-change="changeSearchCheck"
            max-height="290">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="name" :label="$t('user_selection_dep_user')"></el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="getData"
            :current-page.sync="allId.pageNum"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="allId.pageSize"
            layout="prev, pager, next, total, sizes"
            background
            :total="tableData.rowCount?tableData.rowCount:0"
          ></el-pagination>
        </el-tab-pane>
      </el-tabs>
      <el-table :data="checkedUser" max-height="403" class="user_content_selected" >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" :label="$t('selected_user')"></el-table-column>
        <el-table-column align="right">
          <template slot="header" slot-scope="scope">
            <el-button size="small" @click="removeAll(scope.row)">{{$t('remove_all')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-container>
    </dialog_item>
</template>

<script>
export default {
  props: ["flowPreUser","visible","allId"],

  data() {
    let checkeduser=[],checkeduser2=[];
    this.flowPreUser.forEach((el)=>{
      checkeduser.push(el.id)
      checkeduser2.push({id:el.id,name:el.name})
    })

    return {
      defaultExpandedKeys: [],
      node:[],
      resolve:function(){},
      isFirst:true,
      roleData: {},
      onlineData: {},
      searchdata: {
        domainid: "",
        superiorname: "",
        departmentid: "",
        name: "",
        loginno: "",
        roleid: "",
        currpage: 1,
        pagelines: 10,
        orderby: ""
      },
      tableData: [],
      tableDatabyRole: [],
      searchall: false,
      preCheckedUser:checkeduser2,
      checkedUser:checkeduser2,
      
      title:[this.$t('role'),this.$t('selected_user')],
      removeUser:[],
      roleCheck:[],
      deptCheck:[],
      searchCheck:[],
      tab:{},
      timer:'',
      activeName:'byRole',
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      }
    }
  },
  created() {
    this.tab={};
    this.tab.label=this.$t('by_role')
    this.handleClick(this.tab);
    
  },
  methods: {
    onBtnDialogClick(name){
      if(name=='confirm'){
        this.onOk()
      }
    },
    resetSearchTableData(){
      this.allId.selectId='';
      this.getData();
    },
    changeRoleCheck(rows){
      this.roleCheck=rows;
    },
    changeDeptCheck(rows){
      this.deptCheck=rows;
    },
    changeSearchCheck(rows){
      this.searchCheck=rows;
    },
    selectAllChange(selection){
      let that=this;
      if(selection.length>0){
        selection.forEach(el=>{
        let have=false;
        for(let i=0;i<that.checkedUser.length;i++){
          if(el.id==that.checkedUser[i].id){
            have=true;
            break;
          }
        }
        if(!have){
          that.checkedUser.push({id:el.id,name:el.name});
        }
      })
      }else{
        if(this.tab.label==this.$t('by_role')){
          this.tableDatabyRole.datas.forEach((elm)=>{
            let index=null;
            for(let i=0;i<that.checkedUser.length;i++){
              if(elm.id==that.checkedUser[i].id){
                index=i;
                break;
              }
            }
            that.checkedUser.splice(index,1);
          })
        }else if(this.tab.label==this.$t('by_dep')){
          this.tableData.datas.forEach((elm)=>{
            let index=null;
            for(let i=0;i<that.checkedUser.length;i++){
              if(elm.id==that.checkedUser[i].id){
                index=i;
                break;
              }
            }
            that.checkedUser.splice(index,1);
          })
        }else if(this.tab.label==this.$t('query')){
          this.tableData.datas.forEach((elm)=>{
            let index=null;
            for(let i=0;i<that.checkedUser.length;i++){
              if(elm.id==that.checkedUser[i].id){
                index=i;
                break;
              }
            }
            that.checkedUser.splice(index,1);
          })
        }
      }
    },
    removeAll(){
      this.checkedUser=[]
      this.$refs.role.clearSelection()
      this.$refs.dept.clearSelection()

    },
    selectChange(selection,row){
      //判断是否勾选
      let selected = selection.length && selection.indexOf(row) !== -1;
      selection.forEach(el=>{
        let have=false;
        this.checkedUser.forEach(elm=>{
          if(elm.id==el.id){
            have=true;
            return false;
          }
        })
        if(!have){
          this.checkedUser.push({id:el.id,name:el.name});
        }
      })
      //有一个取消勾选
      if(!selected){
        let index=null;
        this.checkedUser.forEach((elm,ind)=>{
          if(elm.id==row.id){
            index=ind;
            return false;
          }
        })
        this.checkedUser.splice(index,1);
      }
    },
    
    onOk() {
      this.dialogVisible = false;
      this.$emit("select-ok", this.checkedUser);
    },
    onCancel() {
      this.dialogVisible = false;
    },
    
    handleClose() {
      this.dialogVisible = false;
    },
    getData(){
      // let that=this;
      this.getAllUsers()
      // if((!that.allId.selectId) && (that.activeName=='byRole'||that.activeName=="byDepartment")){
      //   this.getAllUsers()
      // }else{
      //废弃的接口
      //     this.$api.getFlowUser(this.allId,
      // {
      //   onSucess: resp => {
      //     // this.roleData = resp.data.data;
      //     if(that.tab.label==this.$t('by_role')){
      //       that.tableDatabyRole = resp.data.data;
      //     }
      //     else if(that.tab.label==this.$t('by_dep') || that.tab.label==this.$t('query') ){
      //       that.tableData = resp.data.data;

      //     }
      //   }
      // });
      // }
    },
    handleClick(tab){
      let that=this;
      that.timer = new Date().getTime()
      this.tab=tab;
      if(tab.label==this.$t('by_dep')){
        this.allId.type=1;
        this.allId.pageNum=1;
        this.allId.selectId=''
        this.loadNode(this.node, this.resolve);
        this.getData()
      }
      if(tab.label==this.$t('by_role')){
        this.allId.selectId=''
        this.$api.getRoleList({applicationid: that.allId.applicationId,pagelines:1000000},
        {
          onSucess: resp => {
            this.roleData = resp.data.data;
          }
        });
        this.allId.type=2;
        this.allId.pageNum=1;
        this.getData()
      }
      if(tab.label==this.$t('query')){
        this.allId.type=3;
        this.allId.pageNum=1;
        this.allId.selectId="";
        this.getData();
      }
    },
    
    loadNode(node, resolve) {
      if (node.level === 0) {
        if(this.isFirst){
          this.isFirst=false;
          this.node=node;
          this.resolve=this.resolve;
        }
        this.$api.getRootDepartment(this.$route.query.domainid, {
          onSucess: resp => {
            let rootDepartment = resp.data.data;
            resolve([rootDepartment]);
            this.defaultExpandedKeys.push(rootDepartment.id);
          }
        });
      }
      if (node.level >= 1) {
        this.$api.getSubDepartmentNodes(this.$route.query.domainid, node.key,1, {
          onSucess: resp => {
            let subdepts = resp.data.data;
            resolve(subdepts);
          }
        });
      }
    },
    onNodeClick(dept) {
      this.allId.selectId = dept.id;
      this.getData();
    },
    handleSizeChange(size){
      this.allId.pageNum=1;
      this.allId.pageSize=size;
      this.getData();
    },
    

    roleRowClick(row){
      this.allId.selectId = row.roleId;
      this.getData();
    },
    roleUserSizeChange(size){
      this.allId.pageSize=size;
      this.getData();
    },
   getAllUsers() {
    let searchData= {
        domainid: this.$route.query.domainid,
        departmentid: this.activeName=='byDepartment' ? this.allId.selectId : '',
        currpage: this.allId.pageNum,
        pagelines: this.allId.pageSize,
        orderby: "",
        data:{
          name: this.activeName=='byQuery' ? this.allId.selectId : '',
          loginno: "",
          superiorname: "",
          roleid: this.activeName=='byRole' ? this.allId.selectId : '',
        }
      }; 
      this.$api.getUsers(searchData, {
        onSucess: resp => {
          if(this.activeName=='byDepartment'|| this.activeName=='byQuery'){
            this.tableData=resp.data.data
          }
          else  if(this.activeName=="byRole"){
            this.tableDatabyRole=resp.data.data
          }
        }
      });
    },
  },

};
</script>

<style>

</style>